<template>
  <a-card title="导出任务">
    <a slot="extra" type="link" @click="exportTaskIndex" >{{ __('任务中心') }}</a>
    <a-table
      size="small"
     :scroll="{y: 300}"
     :columns="table.columnsData"
     :data-source="table.data"
     :row-selection="table.rowSelection"
     :pagination="false"/>
    <a-form layout="inline" :form="form" ref="form">
      <a-form-item>
        <a-input
          v-decorator="['filename', { rules: [ { required: true, message: __('导出文件名称不能为空') } ], initialValue: filename } ]"
          placeholder="请输入导出文件名称"
          addon-before="导出文件名称"
          addon-after=".csv"
        />
      </a-form-item>
      <a-form-item>
        <a-button-group>
          <a-button type="primary" :disabled="buttonDisabled" :loading="button.pageExportTask.loading" @click="exportTaskByPageData">{{ __('导出当前页面数据') }}</a-button>
          <a-button type="primary" :disabled="buttonDisabled" :loading="button.serverExportTask.loading" @click="exportTaskByServerData">{{ __('导出全部数据') }}</a-button>
        </a-button-group>
      </a-form-item>
    </a-form>
  </a-card>
</template>
<script>
import api from '@/api'
import Utils from '@/components/YS/Utils'
import { saveAs } from 'file-saver'

export default {
  name: 'ExportTask',
  props: {
    dialogVm: {
      type: Object,
      default: null
    },
    response: {
      type: Object,
      default: null
    },
    columns: {
      type: Array,
      default: Array
    },
    filename: {
      type: String,
      default: null
    }
  },
  data () {
    return {
      card: {
        loading: true
      },
      form: this.$form.createForm(this),
      button: {
        disabled: false,
        serverExportTask: {
          loading: false
        },
        pageExportTask: {
          loading: false
        }
      },
      table: {
        columnsData: [
          { title: '选择导出字段', dataIndex: 'name' }
        ],
        data: [],
        rowSelection: {
          selectedRows: [],
          selectedRowKeys: [],
          onChange: (selectedRowKeys, selectedRows) => {
            this.table.rowSelection.selectedRowKeys = selectedRowKeys
            this.table.rowSelection.selectedRows = selectedRows
          }
        }
      }
    }
  },
  computed: {
    'buttonDisabled' () {
      if (this.button.disabled) {
        return this.button.disabled
      }
      return this.table.rowSelection.selectedRowKeys.length <= 0
    }
  },
  mounted () {
    this.columns.map((column, index) => {
      if (column.dataIndex && column.export !== false) {
        column.visible !== false && this.table.rowSelection.selectedRowKeys.push(index)
        column.visible !== false && this.table.rowSelection.selectedRows.push({
          key: index,
          name: column.title,
          dataIndex: column.dataIndex
        })
        this.table.data.push({
          key: index,
          name: column.title,
          dataIndex: column.dataIndex
        })
      }
    })
    this.$on('close', (v) => {
      console.log('close')
    })
  },
  methods: {
    onCancel () {
      console.log('onCancel')
      return true
    },
    exportTaskByServerData (e) {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.button.serverExportTask.loading = true
          this.button.disabled = true
          api.exportTask.add({
            url: this.response.config.url,
            params: this.response.config.params,
            fields: this.table.rowSelection.selectedRows,
            filename: values.filename
          }).then((response) => {
            this.button.serverExportTask.loading = false
            this.button.disabled = false
            this.dialogVm.$emit('close')

            Utils.dialog(this, () => import('./index'), {
              initialFilters: {
                id: response.data.data.row.id
              }
            }, {
              title: this.__('任务中心')
            })
          }).catch(() => {
            this.button.serverExportTask.loading = false
            this.button.disabled = false
          })
        }
      })
    },
    exportTaskByPageData (e) {
      this.form.validateFields((err, values) => {
        if (!err) {
          const filename = values.filename
          this.button.pageExportTask.loading = true
          this.button.disabled = true

          const csvTitle = []
          const csvTitleMap = {}
          const csvContent = []
          this.table.rowSelection.selectedRows.map((row) => {
            csvTitle.push(row.name)
            csvTitleMap[row.dataIndex] = row.name
          })

          csvContent.push(csvTitle.join(','))
          csvContent.push('\n')
          this.response.data.data.rows.map((row) => {
            const csvRow = []
            Object.keys(csvTitleMap).map((key) => {
              csvRow.push((row[key] !== '' && '"' + row[key] + '"') || '')
            })
            csvContent.push(csvRow.join(','))
            csvContent.push('\n')
          })

          saveAs(new File(csvContent, (filename + '.csv'), {
            type: 'text/plain;charset=utf-8'
          }))
          this.button.pageExportTask.loading = false
          this.button.disabled = false
          this.dialogVm.$emit('close')
        }
      })
    },
    exportTaskIndex (e) {
      Utils.dialog(this, () => import('./index'), {
        initialFilters: {}
      }, {
        title: this.__('任务中心')
      })
    }
  }
}
</script>
